<template>
  <div class="map-container">
    <div class="map" :style="{ width: width, height: height }" :id="mapId"></div>
    <div class="top">
      <div class="search">
        <div class="tip">请输入关键字</div>
        <input id="tipinput" type="text" />
      </div>
      <div id="output"></div>
    </div>

    <div class="edit" @click="onClickBtn">{{ isEdit ? '结束编辑' : '开始编辑' }}</div>
  </div>
</template>

<script>
function isTwoDimensionalArray(arr) {
    return Array.isArray(arr) && arr.every(item => Array.isArray(item));
}
export default {
  name: 'editMap',
  props: {
    /* 高度 */
    width: {
      type: String,
      default: '100%'
    },
    /* 高度 */
    height: {
      type: String,
      default: '200px'
    },
    /* 点位 */
    value: {
      type: String,
      default: null
    },
    /* 类型 1点位  2面积 */
    type: {
      type: Number,
      default: null
    },
    /* 半径 */
    radius: {
      type: Number,
      default: 0
    }
  },
  watch: {
    value: {
      handler(val) {
        if (!val) {
            this.locations = []
            return
        };
        try {
          const arr = JSON.parse(val);
          if (typeof arr[0] == 'object') {
            this.locations = arr.map((item) => {
              return this.GPS.WGS84toGCJ02(...item);
            });
          } else {
            this.locations = this.GPS.WGS84toGCJ02(...arr);
          }
        } catch (e) {
          this.locations = [];
        }
        this.create();
      },
      immediate: true
    },
    type: {
      handler(val) {
        this.create();
      },
      immediate: true
    },
    radius: {
      handler(val) {
        this.circle && this.circle.setRadius(val);
      },
      immediate: true
    }
  },
  data() {
    return {
        polygon: null,
        marker: null,
        circle: null,
        auto: null,
      locations: [],
      isEdit: false,
      mapId: 'map' + new Date().getTime() + parseInt(Math.random() * 1000)
    };
  },
  mounted() {
    if (window.AMap) {
      this.initMap();
    } else {
      window.addEventListener('mapReady', this.initMap);
    }
  },
  beforeDestroy() {
    this.map && this.map.destroy();
    this.polygonEditor = null;
    this.polygon = null;
    window.removeEventListener('mapReady', this.initMap);
  },
  methods: {
    onClickBtn() {
      if (!this.type) {
        this.$modal.msgWarning('请先选择类型');
        return;
      }
      if (this.isEdit) {
        // 结束编辑
        let arr = [];
        if (this.type == 1) {
          const point = this.marker.getPosition();
          this.locations = [point.lng, point.lat];
          arr = this.GPS.GCJ02toWGS84(point.lng, point.lat);
        } else {
          this.polygonEditor.close();
          this.polygonEditor.clearAdsorbPolygons();
          this.polygon = this.polygonEditor.getTarget();
          const points = this.polygon.getPath();
          this.locations = points.map((point) => [point.lng, point.lat]);
          arr = points.map((point) => {
            return this.GPS.GCJ02toWGS84(point.lng, point.lat);
          });
        }
        this.$emit('input', JSON.stringify(arr));
      } else {
        // 开始编辑
        if (this.type == 1) {
          if (!this.mouseTool) this.mouseTool = new AMap.MouseTool(this.map);
          if (!this.marker) {
            this.mouseTool.marker();
            this.mouseTool.on('draw', (e) => {
              const point = e.obj.getPosition();
              if (this.marker) {
                this.map.remove(e.obj);
                this.marker.setPosition(point);
                this.circle.setCenter(point);
              } else {
                this.marker = e.obj;
                this.createCircle(point);
              }
            });
          }
        } else {
            this.polygonEditor = new AMap.PolygonEditor(this.map);
        //   if (!this.polygonEditor) this.polygonEditor = new AMap.PolygonEditor(this.map);
          this.polygon && this.polygonEditor.setTarget(this.polygon);
          this.polygonEditor.open();
        }
      }
      this.isEdit = !this.isEdit;
    },
    initMap() {
      // console.log('初始化地图：', this.map);
      if (this.map) {
        this.map.destroy();
        this.map = null;
      };
      if(this.auto) {
        this.auto.off("select");
        this.auto = null;
      }
      // 动态添加属性，防止Vue监听
      this.map = new AMap.Map(this.mapId, {
        mapStyle: 'amap://styles/normal',
        viewMode: '2D', //是否为3D地图模式
        zoom: 12, //初始化地图级别
        center: [120.14, 30.32] //初始化地图中心点位置
      });
      // 卫星地图切换
      this.map.addControl(new AMap.MapType());
      // 输入提示
      this.auto = new AMap.AutoComplete({
        input: 'tipinput',
        output: 'output'
      });
      var placeSearch = new AMap.PlaceSearch({
        map: this.map
      }); //构造地点查询类
      this.auto.on('select', select); //注册监听，当选中某条记录时会触发
      function select(e) {
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name); //关键字查询查询
      }
      this.create();
    },
    create() {
      if (!this.map) return;
      this.remove();
      if (this.type == 1) {
        this.createMarker(this.locations);
        this.createCircle(this.locations);
      } else {
        this.createPolygon(this.locations);
      }
    },
    // 创建面
    createPolygon(path) {
      if (!path || path.length <= 3) return;
      this.polygon = new AMap.Polygon({
        path: path,
        strokeColor: '#f00',
        fillColor: '#ff0',
        fillOpacity: 0.5
      });
      this.map.add(this.polygon);
      this.map.setFitView(this.polygon);
    },
    // 创建点位
    createMarker(path) {
        console.log('path-----', path)
      if (!path || path.length <= 1) return;
      this.marker = new AMap.Marker({
        position: path,
        title: '打卡地点',
        draggable: true,
        label: {
          content: '打卡地点',
          direction: 'top'
        }
      });
      this.map.add(this.marker);
      this.map.setFitView(this.marker);
    },
    // 创建圆形
    createCircle(path) {
      if (!path || path.length <= 1) return;
      this.circle = new AMap.Circle({
        center: path, //圆心
        radius: this.radius, //半径
        strokeColor: '#FF33FF',
        strokeWeight: 2,
        fillColor: '#1791fc',
        fillOpacity: 0.4,
        strokeStyle: 'dashed'
      });
      this.map.add(this.circle);
    },
    remove() {
        if(this.polygon) {
            this.map.remove(this.polygon);
            this.polygon = null;
        }
        if(this.marker) {
            this.map.remove(this.marker);
            this.marker = null;
        }
        if(this.circle) {
            this.map.remove(this.circle);
            this.circle = null;
        }
    }
  }
};
</script>

<style scoped lang="scss">
.map-container {
  position: relative;

  .edit {
    position: absolute;
    bottom: 20px;
    left: 20px;
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
    cursor: pointer;
  }

  .top {
    position: absolute;
    top: 20px;
    left: 20px;
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  }

  .search {
    display: flex;

    .tip {
      padding: 0 5px;
      color: #495057;
      text-align: center;
      height: 30px;
      line-height: 30px;
      white-space: nowrap;
      background-color: #e9ecef;
      border: 1px solid #ced4da;
      border-right: none;
      border-radius: 5px;
      border-bottom-right-radius: 0;
      border-top-right-radius: 0;
    }

    input {
      outline-style: none;
      width: 200px;
      height: 30px;
      line-height: 30px;
      border-radius: 5px;
      border: 1px solid #ced4da;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      background: #fff;
      padding:0 5px;
      margin: 0;
    }
  }

  .map {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
  }
}
</style>
